export default {
	namespaced: true,
	state: () => ({
		cartList: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	mutations: {
		deleteGoods(state, goods) {
			state.cartList = state.cartList.filter(s => s.goodsId !== goods.goodsId)
			this.commit('cart/saveToStorage')

		},
		updateCount(state, goods) {
			const res = state.cartList.find(s => s.goodsId === goods.goodsId)
			if (res) {
				res.goods_count = goods.goods_count
				this.commit('cart/saveToStorage')
			}
		},
		updateState(state, goods) {
			const res = state.cartList.find(s => s.goodsId === goods.goodsId)
			if (res) {
				res.goods_state = !res.goods_state
				this.commit('cart/saveToStorage')
			}
		},
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cartList))
		},
		addToCart(state, goods) {
			const res = state.cartList.find(x => x.goodsId === goods.goodsId)
			if (!res) {
				state.cartList.push(goods)
			} else {
				res.goods_count = res.goods_count + 1
			}
			console.log(state.cartList)
			this.commit('cart/saveToStorage')
		},
		updateAllState(state, newState) {
			state.cartList.forEach(s => s.goods_state = newState)
			this.commit('cart/saveToStorage')
		}
	},
	getters: {
		allCheckedPriceTotal(state) {
			let c = 0
			state.cartList.forEach(s => {
				if (s.goods_state) {
					c += s.goods_count * s.goodsPrice
				}
				
			})
			return c
		},
		total(state) {
			let c = 0
			state.cartList.forEach(s => c += s.goods_count)
			return c
		},
		checkedCount(state) {
			let c = 0
			state.cartList.forEach(s => {
				if (s.goods_state) {
					c += s.goods_count
				}
			})
			return c
		}

	}
}